import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;

import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Fileupload;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listhead;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.SimpleListModel;


public class UploadProcessor extends GenericForwardComposer
{
	private Fileupload fileUpload;
	private Listbox emaillistbox;
	private Label numemail;
		
	public void onUpload$fileUpload( UploadEvent event )
	{
		Media media = event.getMedia();
		
		if( media != null )
		{
			String data = media.getStringData();
			
			if( data.length() > 200 * 1024 )
			{
				try 
				{
					Messagebox.show( "Max file size is 200KB", "File Upload Failed", Messagebox.OK, Messagebox.ERROR );
				} 
				catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				return;
			}
			
			List<String> listEmails = GetEmailsFromText( data );
			
			ListModel listModel = new SimpleListModel( listEmails );			
			emaillistbox.setModel( listModel );
			
			numemail.setValue( "Number of Emails: " + listEmails.size() );	
			numemail.setVisible( true );
			
		}
	}

	private List GetEmailsFromText(String data) 
	{
		// TODO Auto-generated method stub
		List<String> emails = new ArrayList<String>();
		
		StringTokenizer st = new StringTokenizer( data, "\n" );
		
		while( st.hasMoreTokens() )
		{
			String token = st.nextToken();
			
			if( token.startsWith( "EMAIL" ) )
			{
				int markerIndex = token.indexOf( ':' );
				
				if( markerIndex >= 0 )
				{
					String email = token.substring( markerIndex + 1 );
					emails.add( email );
				}
			}
		}
		
		return emails;
	}
}
